package com.kalvan.web.servlet.response;

import com.alibaba.fastjson.JSON;
import com.kalvan.client.context.RequestContext;
import com.kalvan.client.context.RequestContextHolder;
import com.kalvan.client.model.ApiResponse;
import com.kalvan.client.model.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 统一返回数据扩展
 *
 * @author chenliang
 */
@Slf4j
public class ResponseHandler implements ResponseBodyAdvice {
    public ResponseHandler() {
        log.info("init ResponseHandler...");
    }

    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        log.info("返回结果:{}", JSON.toJSONString(o));
        RequestContext context = RequestContextHolder.getContext();
        if (context == null) {
            log.debug("上下文对象为空");
            return o;
        }
        Object data = o;
        if (o instanceof ApiResponse) {
            data = ((ApiResponse<?>) o).getData();
        }
        if (data instanceof Response) {
            context.setSuccess(((Response<?>) data).success());
            context.setResponseCode(((Response<?>) data).getCode());
            context.setResponseDesc(((Response<?>) data).getDesc());
        }
        return o;
    }
}
